package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Purchase;
import io.wins.vertx.service.PurchaseService;

public class PurchaseApiVerticle extends RestApiVerticle {

    public static final String REST_ADDRESS = "io.wins.rest.purchase#%1$s";
    public static final String STATUS = "STATUS";
    private static final Logger logger = LoggerFactory.getLogger(PurchaseApiVerticle.class);

    public final PurchaseService service;

    public PurchaseApiVerticle(final PurchaseService purchaseService) {
        this.service = purchaseService;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        super.start();
        this.on(String.format(REST_ADDRESS, CREATE), this::createPurchase);
        this.on(String.format(REST_ADDRESS, LIST), this::listPurchase);
        this.on(String.format(REST_ADDRESS, UPDATE), this::updatePurchase);
        this.on(String.format(REST_ADDRESS, DELETE), this::deletePurchase);
        this.on(String.format(REST_ADDRESS, STATUS), this::updateStatus);
        startFuture.complete();
    }

    private void updatePurchase(final Message<JsonObject> tMessage) {
    }

    private void deletePurchase(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("param").getString("id");
        this.service.delPurchase(id, tMessage);
    }

    private void updateStatus(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("body").getString("id");
        final String status = tMessage.body().getJsonObject("body").getString("status");
        this.service.updateStatus(id, status, tMessage);
    }

    private void listPurchase(final Message<JsonObject> tMessage) {
        final String status = tMessage.body().getJsonObject("body").getString("status");
        this.service.listPurchase(status, tMessage);
    }

    private void createPurchase(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("purchase");
        final Purchase purchase = new Purchase(body);
        this.service.createPurchase(purchase, tMessage);
    }
}
